package com.yzy.agent;

import com.yzy.agent.DynamicAgent.CGLIBAgent;
import com.yzy.agent.DynamicAgent.JDKAgent;
import com.yzy.agent.staticAgent.Agent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.TreeMap;


/**
 * Description:
 * Date: 2019-08-28
 *
 * @author youzhiyong
 */
public class Test {

    public static void main(String[] args) {
        // 静态代理
        Fruit fruit = new Agent(new Apple());
        fruit.show();

        //动态代理 - JDK
        Fruit fruit1 = (Fruit) JDKAgent.getAgent(Fruit.class, new Apple());
        fruit1.show();

        //动态代理 - JDK2
        //被代理对象
        Fruit agent = new Apple();
        Fruit fruit11 = (Fruit) Proxy.newProxyInstance(
                //1. 类加载器
                Fruit.class.getClassLoader(),
                //2. 代理类的所有接口列表
                new Class[]{Fruit.class},
                //3. 继承InvocationHandler类，并实现invoke方法
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("begin proxy");
                        method.invoke(agent, args);
                        System.out.println("end proxy");
                        return null;
                    }
                });
        fruit11.show();

        //动态代理 - CGLIB
        Fruit fruit2 = (Fruit) new CGLIBAgent().getAgent(new Apple());
        fruit2.show();

    }

}
